import { useState, useEffect } from "react";
import Taro from "@tarojs/taro";
import { View } from "@tarojs/components";
import Card from "../component/card";
import Utils from "@/utils/index";
import LgSearch from "@/pages/components/searchInput";
import { useDispatch } from "react-redux";
import Empty from "@/pages/components/emptyContent";
import { connect } from "react-redux";
import _ from "lodash";
import { SwipeAction } from "antd-mobile";
import { useGetClientType, useSendSocketMsg } from "@/utils/myUtils";
import useToChatPage from "../../../hooks/useToChatPage";
import "./index.scss";

const { getChatTime } = Utils;

let ClientType = useGetClientType();

function App(props) {
  let { userInfo, sessionList, token, lg_ic, env, chatUrl } = props;

  const [keyword, setKeyword] = useState("");

  const dispatch = useDispatch();

  const computeSwipe = (item) => {
    //计算滑块的操作项
    if (item.sessionType == 2) {
      if (item.remind == 0) {
        return [
          {
            key: "noDisturb",
            text: "消息提醒",
            color: "#f6ab3b",
            onClick: () => noDisturbHandle(item),
          },
          {
            key: "delete",
            text: "移除",
            color: "#e75d58",
            onClick: () => delHandle(item),
          },
        ];
      } else {
        return [
          {
            key: "noDisturb",
            text: "消息免打扰",
            color: "#f6ab3b",
            onClick: () => noDisturbHandle(item),
          },
          {
            key: "delete",
            text: "移除",
            color: "#e75d58",
            onClick: () => delHandle(item),
          },
        ];
      }
    } else {
      /* isShield是否屏蔽 isNodisturb是否消息免打扰 */
      if (item.block && item.remind == 0) {
        //处于屏蔽+免打扰
        return [
          {
            key: "noShield",
            text: "取消屏蔽",
            color: "#009cff",
            onClick: () => shieldHandle(item),
          },
          // {
          //   key: 'noDisturb',
          //   text: '消息提醒',
          //   color: '#f6ab3b',
          //   onClick: () => noDisturbHandle(item)
          // },
          {
            key: "delete",
            text: "移除",
            color: "#e75d58",
            onClick: () => delHandle(item),
          },
        ];
      } else if (item.block && item.remind == 1) {
        //处于屏蔽 + 非免打扰
        return [
          {
            key: "noShield",
            text: "取消屏蔽",
            color: "#009cff",
            onClick: () => shieldHandle(item),
          },
          // {
          //   key: 'noDisturb',
          //   text: '消息免打扰',
          //   color: '#f6ab3b',
          //   onClick: () => noDisturbHandle(item)
          // },
          {
            key: "delete",
            text: "移除",
            color: "#e75d58",
            onClick: () => delHandle(item),
          },
        ];
      } else if (!item.block && item.remind == 0) {
        //处于非屏蔽 + 免打扰
        return [
          {
            key: "noShield",
            text: "屏蔽此人",
            color: "#009cff",
            onClick: () => shieldHandle(item),
          },
          {
            key: "noDisturb",
            text: "消息提醒",
            color: "#f6ab3b",
            onClick: () => noDisturbHandle(item),
          },
          {
            key: "delete",
            text: "移除",
            color: "#e75d58",
            onClick: () => delHandle(item),
          },
        ];
      } else {
        //处于非屏蔽 + 非免打扰
        return [
          {
            key: "noShield",
            text: "屏蔽此人",
            color: "#009cff",
            onClick: () => shieldHandle(item),
          },
          {
            key: "noDisturb",
            text: "消息免打扰",
            color: "#f6ab3b",
            onClick: () => noDisturbHandle(item),
          },
          {
            key: "delete",
            text: "移除",
            color: "#e75d58",
            onClick: () => delHandle(item),
          },
        ];
      }
    }
  };

  // 去聊天
  const toChatPage = (item, chatType) => {
    let chatId = item.receiverId || item.groupId;
    let chatName = item.receiverName || item.groupName;
    let chaturl = "";

    if (!chatUrl) {
      Taro.showToast({
        title: "暂无在线交流地址",
        icon: "none",
      });
      return;
    }

    let data: any = {
      sessionType: chatType,
      receiverId: chatId,
    };

    if (chatType == 2) {
      data = {
        sessionType: chatType,
        groupId: chatId,
      };
    }

    let sendObj = {
      msgType: "13",
      clientType: ClientType,
      token: token,
      data: data,
    };
    useSendSocketMsg(sendObj);

    // if (process.env.NODE_ENV === "development") {
    //   chaturl = `http://192.168.129.86:10091/?lg_tk=${token}&lg_ic=${lg_ic}&chatId=${chatId}&chatName=${chatName}&chatType=${chatType}&env=${env}&schoolId=${userInfo.SchoolID}`;
    // } else {
    // chaturl = `${chatUrl}/mobile/index.html?lg_tk=${token}&lg_ic=${lg_ic}&chatId=${chatId}&chatName=${chatName}&chatType=${chatType}&env=${env}&schoolId=${userInfo.SchoolID}`;
    // if (Utils.getSystemInfo() === "weapp") {
    //   //124环境才有在线交流外网
    //   chaturl = proxy.transmitUrlToVisit(chaturl);
    // }
    // // }

    // window.open(chaturl, "_self");
    useToChatPage(item,chatType,chatUrl,token,lg_ic,userInfo.schoolId)
  };

  // 搜索聊天
  const searchHandle = _.debounce((value) => {
    setKeyword(value.trim());
  }, 500);

  //更新搜索列表
  const updateList = () => {
    if (!keyword) {
      //清空当前的搜索 重新获取会话
      useSendSocketMsg({
        msgType: 4,
        clientType: ClientType,
        token: token,
        data: {},
      });
    }
    if (sessionList.length == 0) {
      return;
    }

    let newList = sessionList.filter((item) => {
      return (
        item?.receiverName?.includes(keyword) ||
        item?.groupName?.includes(keyword)
      );
    });
    // console.log('newList', newList);
    dispatch({ type: "SESSIONLIST", data: newList });
  };

  // 屏蔽
  const shieldHandle = (item) => {
    let sendObj = {
      msgType: "11",
      clientType: ClientType,
      token: token,
      data: {
        sessionId: item.sessionId,
        block: item.block == 1 ? 0 : 1,
      },
    };
    useSendSocketMsg(sendObj);
  };

  const delHandle = (item) => {
    let sendObj;
    sendObj = {
      msgType: 7,
      clientType: ClientType,
      token: token,
      data: {
        sessionId: item.sessionId,
      },
    };
    Taro.showModal({
      title: "提示",
      content: "是否移除当前会话",
      confirmColor: "#0099ff",
      success: function (res) {
        if (res.confirm) {
          useSendSocketMsg(sendObj);
        } else if (res.cancel) {
          console.log("用户点击取消");
        }
      },
    });
  };

  const noDisturbHandle = (item) => {
    let sendObj = {
      msgType: "12",
      clientType: ClientType,
      token: token,
      data: {
        sessionId: item.sessionId,
        remind: item.remind == 0 ? 1 : 0,
      },
    };
    useSendSocketMsg(sendObj);
  };

  useEffect(() => {
    updateList();
  }, [keyword]);

  return (
    <View className="online_container">
      <View className="online_header">
        <LgSearch
          placeholder="搜索..."
          onInput={searchHandle}
          value={keyword}
          onConfirm={(value: string) => setKeyword(value.trim())}
        />
      </View>
      <View>
        <View
          className={
            Utils.getSystemInfo() === "weapp" ? "mes_body weapp" : "mes_body"
          }
        >
          {sessionList.length > 0 ? (
            sessionList.map((item, index) => {
              return (
                <View key={index}>
                  <SwipeAction rightActions={computeSwipe(item)}>
                    <Card
                      type="D"
                      isNodisturb={item.remind == 0 ? true : false}
                      isShield={item.block == 1 ? true : false}
                      senderName={item.receiverName || item.groupName}
                      groupSender={item.NewestMsgSenderName}
                      senderPhoto={item.receiverAvatarPath}
                      msgContent={item.lastMsg}
                      unreadMsgCount={item.unReadCount}
                      msgType={item.NewestMsgType}
                      NewestMsgIsRevoke={item.NewestMsgIsRevoke}
                      NewestMsgSenderID={item.NewestMsgSenderID}
                      time={getChatTime(item.updated)}
                      groupName={item.groupName ? item.groupName : ""}
                      onClick={() => {
                        toChatPage(item, item.sessionType);
                      }}
                      id={item.sessionId}
                      shieldHandle={() => {
                        shieldHandle(item);
                      }}
                      delHandle={() => {
                        delHandle(item);
                      }}
                      noDisturbHandle={() => {
                        noDisturbHandle(item);
                      }}
                      detail={item}
                      sessionType={item.sessionType}
                    />
                  </SwipeAction>
                </View>
              );
            })
          ) : (
            <Empty type="B" text="暂无聊天记录" />
          )}
        </View>
      </View>
    </View>
  );
}

const mainProps = ({ commonData, sessionList }) => {
  return {
    userInfo: commonData.userInfo,
    sessionList: sessionList,
    mainServer: commonData.mainServer,
    token: commonData.token,
    lg_ic: commonData.lg_ic,
    env: commonData.env,
    chatUrl: commonData.chatUrl,
  };
};

export default connect(mainProps)(App);
